package com.mtt.erp.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.mtt.erp.common.exception.MttErpException;
import com.mtt.erp.common.utils.MttErpUtil;
import com.mtt.erp.common.utils.QCloudOssUtils;
import com.mtt.erp.file.FileConfig;
import com.mtt.erp.file.dao.GoodsFileInfoMapper;
import com.mtt.erp.file.domain.GoodsFileInfo;
import com.mtt.erp.file.dto.ImageDto;
import com.mtt.erp.file.service.GoodsFileInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @Auther: SJZ    2907374717@qq.com
 * @Date: 2019/5/30 13:21
 * @Description:
 */
@Service
@Slf4j
public class GoodsFileInfoServiceImpl extends ServiceImpl<GoodsFileInfoMapper, GoodsFileInfo> implements GoodsFileInfoService {
    @Value("${file.upload.directory}")
    private String fileUploadDirectory;

    @Override
    @Transactional
    public Boolean uploadQCloud(MultipartFile file) throws MttErpException {
        String userName = MttErpUtil.getCurrentUser().getUsername();
        String key = "/" + userName + "/" + file.getOriginalFilename();
        GoodsFileInfo goodsFileInfo = GoodsFileInfo.builder().creator(userName).fileKey(key).build();
        Integer count = countFile(goodsFileInfo);
        if (count > 0) {
            log.error("文件已存在");
            // 20002图片已存在
            throw new MttErpException("20002");
        } else {
            goodsFileInfo.setFileKey(key);
            goodsFileInfo.setCreateTime(LocalDateTime.now());
            Boolean addResult = this.save(goodsFileInfo);
            if (addResult) {
                String fileName = file.getOriginalFilename();
                File localFile = new File(fileUploadDirectory + "\\" + fileName);
                try {
                    file.transferTo(localFile);
                } catch (IOException e) {
                    log.error("文件上传异常");
                    // 20001 系统异常
                    throw new MttErpException("20001");
                }
                QCloudOssUtils.upload(localFile, key);
                QCloudOssUtils.shutDown();
                return true;
            } else {
                log.error("文件上传失败");
                return false;
            }
        }
    }

    @Override
    public Boolean addGoodsFileInfo(GoodsFileInfo goodsFileInfo) {
        goodsFileInfo.setCreateTime(LocalDateTime.now());
        String userName = MttErpUtil.getCurrentUser().getUsername();
        goodsFileInfo.setCreator(userName);
        return this.save(goodsFileInfo);
    }

    @Override
    public List<ImageDto> findImageList(List<String> ids) {
        QueryWrapper<GoodsFileInfo> queryWrapper = new QueryWrapper<>();
        if (ids !=null && ids.size()>0) {
            queryWrapper.lambda().in(GoodsFileInfo::getId, ids);
        }
        List<ImageDto> list = Lists.newArrayList();
        List<GoodsFileInfo> goodsFileInfos = baseMapper.selectList(queryWrapper);

        for (GoodsFileInfo goodsFileInfo : goodsFileInfos) {
            String fileKey = goodsFileInfo.getFileKey();
            list.add(ImageDto.builder().uid(goodsFileInfo.getId())
                    .url(FileConfig.goodImageDomain + fileKey)
                    .thumbUrl(FileConfig.goodImageDomain + fileKey)
                    .status("done")
                    .name(fileKey)
                    .build());
        }
        return list;
    }

    @Override
    public List<ImageDto> findImageListByIkeyS(List<String> keys) {
        QueryWrapper<GoodsFileInfo> queryWrapper = new QueryWrapper<>();
        if (keys !=null && keys.size()>0) {
            queryWrapper.lambda().in(GoodsFileInfo::getFileKey,keys);
        }
        List<ImageDto> list = Lists.newArrayList();
        List<GoodsFileInfo> goodsFileInfos = baseMapper.selectList(queryWrapper);
        for (GoodsFileInfo goodsFileInfo : goodsFileInfos) {
            String fileKey = goodsFileInfo.getFileKey();
            list.add(ImageDto.builder().uid(goodsFileInfo.getId())
                    .url(FileConfig.goodImageDomain + fileKey)
                    .thumbUrl(FileConfig.goodImageDomain + fileKey)
                    .status("done")
                    .name(fileKey)
                    .build());
        }
        return list;
    }

    @Override
    public Integer countFile(GoodsFileInfo goodsFileInfo) {
        String fileKey = goodsFileInfo.getFileKey();
        String userName = goodsFileInfo.getCreator();
        QueryWrapper<GoodsFileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(GoodsFileInfo::getFileKey, fileKey).eq(GoodsFileInfo::getCreator, userName);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    @Transactional
    public Boolean deleteFile(String fileKeyStr) throws MttErpException {
        String userName = MttErpUtil.getCurrentUser().getUsername();
        List<String> fileKeys = Arrays.asList(fileKeyStr.split(StringPool.COMMA));
        for (String fileKey :fileKeys) {
            QueryWrapper<GoodsFileInfo> queryWrapper= new QueryWrapper<>();
            queryWrapper.lambda().eq(GoodsFileInfo::getFileKey,fileKey).eq(GoodsFileInfo::getCreator,userName);
            try {
                baseMapper.delete(queryWrapper);
                QCloudOssUtils.deleteObject(fileKey);
            }catch (Exception e){
                log.error("删除文件失败");
                throw new MttErpException("删除文件失败");
            }
        }
        return true;
    }
}
